package com.example.springbootvalidation.utils;

import com.example.springbootvalidation.result.CodeMsg;
import com.example.springbootvalidation.result.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BindingResultUtil {

    /**
     * 多个参数验证提示
     * @param bindingResult
     * @return
     */
    public static Result bindingResults(BindingResult bindingResult){
        Map<String, String> errorMsg = new HashMap<String, String>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for(FieldError fieldError:fieldErrors){
            errorMsg.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Result.error(CodeMsg.BIND_ERROR.fillArgs(errorMsg));
    }

    /**
     * 单个参数验证提示
     * @param bindingResult
     * @return
     */
    public static Result bindingResult(BindingResult bindingResult){
        return Result.error(CodeMsg.BIND_ERROR.fillArgs(bindingResult.getFieldError().getDefaultMessage()));
    }
}
